<script lang="ts" setup>
import * as Yup from 'yup'
import ResolveLocked from './_comp/ResolveLocked.vue'

defineOptions({
  name: 'LoginSignIn',
})
definePageMeta({
  layout: 'other',
})

const router = useRouter()
const appStore = useAppStore()
const { countryCallingCode } = useIpApi()
// todo
// const { brandReg, isLoginPWAOpen } = storeToRefs(useBrandStore())
const { areaCodeOptionsFiltered } = useAreaCode()

const isPhoOrEma = ref<'p' | 'e'>('e')
const userOrEmail = ref('')
const phone = ref('')
const password = ref('')
const isPop = ref(false)

const { open } = useDialog(ResolveLocked, null, { showClose: true, title: $t('resolve_locked'), size: ['90%', '18.75rem'] })
const areaCode = ref(countryCallingCode.value)

const { run: runMemberLogin, loading: isLoading } = useRequest(
  async data =>
    ApiMemberLogin({
      ...data,
      device_number: await application.getDeviceNumber(),
    }),
  {
    manual: true,
    onSuccess: async (res: string) => {
      console.log('res', res)
      Local.set(STORAGE_LOGIN_MQTT_ID, Math.floor(Math.random() * 100))
      Local.remove(STORAGE_PROMO_AD_POP_LOGIN)

      await nextTick()
      appStore.setToken(res)
      i18nNavigateTo('/casino')
      message.success($t('success_login'))

      // setTimeout(() => {
      // // 打开登陆PWA
      //   if (isLoginPWAOpen.value && !isPwa())
      //     openLoginPwaDialog()
      // }, 300)
    },
    onError: (err) => {
      const { data, tip } = JSON.parse(err.message)
      if (data == 'member-verify') {
        // todo 长时间未登录验证
        goLong(tip)
        message.error($t('your_account_was_locked'))
      }
    },
  },
)
const { captchaButtonId, captchaEleId, showCaptcha } = useAliCaptcha({
  success: () => {
    let num = ''
    if (isPhoOrEma.value == 'p') {
      num = dealNumber(phone.value)
    }
    else {
      num = userOrEmail.value
    }
    runMemberLogin({
      username: num,
      password: password.value,
    })
  },
})
const schema = Yup.object().shape({
  userOrEmail: Yup.string(),
  phone: Yup.string(),
  password: Yup.string(),
})
function validEmail(value: string) {
  if (value.length < 3)
    return $t('pop_up_login_first_input_min_length', { delta: 3 })
  else if (value.length > 30)
    return $t('max_len_char', { delta: 30 })
  else if (value.match('[^@.a-zA-Z0-9_]'))
    return $t('name_has_invalid_char')
  else if (!emailReg.test(value) && !usernameReg.test(value))
    return $t('validate_msg_user_name')
  return ''
}
function validPhoneVal(value: string) {
  let result
  if (areaCode.value === '+63') {
    result
        = philippinePhoneReg.test(`+63${value}`) && value.length > 5 && value.length <= 18
        ? ''
        : $t('phone_invalid')
  }
  else if (areaCode.value === '+86') {
    result
        = chinaPhoneReg.test(`${value}`) && value.length > 5 && value.length <= 18
        ? ''
        : $t('phone_invalid')
  }
  else if (areaCode.value === '+55') {
    result
        = brazilPhoneReg.test(`+55${value}`) && value.length > 5 && value.length <= 18
        ? ''
        : $t('phone_invalid')
  }
  else {
    result
        = numberReg.test(value) && value.length > 5 && value.length <= 18 ? '' : $t('phone_invalid')
  }
  return result
}

function onValidNum() {
  let res = ''
  if (isPhoOrEma.value === 'p') {
    res = validPhoneVal(phone.value)
  }
  else {
    res = validEmail(userOrEmail.value)
  }
  if (res) {
    return res
  }
}
function dealNumber(v: string) {
  return isPhoOrEma.value == 'e' ? v : `${areaCode.value}-${v}`
}

function onSubmit() {
  const val = onValidNum()
  if (val) {
    message.error(val as string)
    return
  }
  showCaptcha()
}
function onInvalidSubmit(err: any) {
  console.log(err, 'err')
}
function onBack() {
  router.back()
}
function changeLogin() {
  if (isPhoOrEma.value == 'e') {
    isPhoOrEma.value = 'p'
  }
  else {
    isPhoOrEma.value = 'e'
  }
}

function openPop() {
  isPop.value = true
}
function goForget() {
  i18nNavigateTo('/login/forget')
}
function goRegist() {
  i18nNavigateTo('/login/regist')
}
function goLong(data: string) {
  i18nNavigateTo({
    path: '/login/long',
    query: {
      a: data,
      u: userOrEmail.value,
      p: password.value,
    },
  })
}

onMounted(() => {
  areaCode.value = countryCallingCode.value
})
</script>

<template>
  <div class="h-full ">
    <div class="size-full bg-[#232626]">
      <div class="relative w-full">
        <BaseImage url="/images/webp/header/h5-header.png" alt="" class="w-full" />
        <div class="absolute top-0 w-full flex justify-between items-center p-4">
          <div>logo</div>
          <BaseButton
            class="w-7 !h-7 bg-[rgba(255,255,255,.05)] rounded"
            type="none"
            @click="onBack"
          >
            <BaseIcon name="uni-close2" class="text-xl scale-50" />
          </BaseButton>
        </div>
      </div>

      <div class="py-5 px-6 relative w-full">
        <div class="flex justify-between w-full mb-3">
          <span class="text-base font-extrabold text-white">{{ $t('signin') }}</span>
        </div>
        <div class="mb-3">
          <BaseForm :schema="schema" autocomplete="off" @submit="onSubmit" @invalid-submit="onInvalidSubmit">
            <BaseInput
              v-if="isPhoOrEma == 'e'"
              name="userOrEmail"
              class="mb-3"
              :model-value="userOrEmail"
              :placeholder="$t('username_or_email_login')"
              :required="true"
              @update:model-value="v => (userOrEmail = v)"
            />
            <BaseInput
              v-else
              name="phone"
              class="mb-3"
              type="number"
              inputmode="number"
              :model-value="phone"
              :placeholder="$t('pls_type_phone_number')"
              :required="true"
              @update:model-value="v => (phone = v)"
            >
              <template #left-icon>
                <BaseButton type="none" class="text-[0.75rem] !p-0">
                  <div class="border-r-[2px] border-[#e4eaf019] pr-1 flex" @click="openPop">
                    {{ areaCode }}<BaseIcon name="uni-arrow-down" class="pl-1" />
                  </div>
                </BaseButton>
              </template>
            </BaseInput>
            <BaseInput
              name="password"
              type="password"
              :required="true"
              :placeholder="$t('password')"
              class="mb-3"
              @update:model-value="v => (password = v)"
            />
            <div class="w-full flex justify-between mb-3">
              <BaseButton type="none" class="h-auto text-xs text-[#A8AEB0]" @click="changeLogin">
                {{ isPhoOrEma == 'e' ? $t('phone_login') : $t('username_or_email_login') }}
              </BaseButton>
              <BaseButton type="none" class="h-auto text-xs text-[#A8AEB0]" @click="goForget">
                {{ $t('forget_password') }}
              </BaseButton>
            </div>
            <BaseButton html-type="submit" :loading="isLoading" type="primary" class="w-full h-[40px] text-xs">
              {{ $t('signin') }}
            </BaseButton>
          </BaseForm>
        </div>
        <div class="flex text-xs font-semibold">
          <span class="text-white">{{ $t('is_new_member') }}</span>
          <BaseButton type="none" class="pl-0 h-auto text-xs text-[#24EE89]" @click="goRegist">
            {{
              $t('register')
            }}
          </BaseButton>
          <BaseButton type="none" class="h-auto ml-auto text-xs" @click="() => open()">
            {{ $t('resolve_locked') }}
          </BaseButton>
        </div>
        <div>
          <AppThirdLogin />
        </div>
        <div>
          <div :id="captchaEleId" />
          <div :id="captchaButtonId" />
          <BaseBob v-model:show="isPop" v-model:selected="areaCode" is-search :header="$t('area_choice')" :need-move="true" :option="areaCodeOptionsFiltered" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
